﻿using System;
using System.Net;
using System.IO;

namespace DemoApp
{
    public static class WebServiceHelper
    {
        public static string ConsumeWebService(string webServiceUri)
        {
            WebRequest req = null;
            WebResponse rsp = null;

            try
            {
                req = WebRequest.Create(webServiceUri);
                //req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
                req.Method = "GET"; // Post method
                req.ContentType = "application/json";  // content type
                // Send the data to the webserver
                rsp = req.GetResponse();
                StreamReader sr = new StreamReader(rsp.GetResponseStream());
                string result = sr.ReadToEnd();
                sr.Close();

                return result;
            }
            catch (WebException)
            {
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static void StoreXMLtoWebService(string xmlFileName, string webServiceUri)
        {
            WebRequest req = null;
            WebResponse rsp = null;

            try
            {
                req = WebRequest.Create(webServiceUri);
                //req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
                req.Method = "POST"; // Post method
                req.ContentType = "application/xml"; // content type
                // Wrap the request stream with a text-based writer
                StreamWriter writer = new StreamWriter(req.GetRequestStream());
                // Write the XML text into the stream
                writer.WriteLine(GetTextFromXMLFile(xmlFileName));
                writer.Close();
                // Send the data to the webserver
                rsp = req.GetResponse();
                StreamReader sr = new StreamReader(rsp.GetResponseStream());
                string result = sr.ReadToEnd();
                sr.Close();
            }
            catch (WebException)
            {
                
            }
            catch (Exception)
            {
                
            }
        }

        private static string GetTextFromXMLFile(string file)
        {
            StreamReader reader = new StreamReader(file);
            string ret = reader.ReadToEnd();
            reader.Close();
            return ret;
        }
    }
}
